package scatter.common.rest.tools;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * Created by yangwei
 * Created at 2019/11/12 17:34
 */
public class RequestIdTool {

    private static final String REQUEST_ID_KEY = "requestIdKey";
    // 请求id，从header中获取
    public static final String REQUEST_ID = "request-id";
    /**
     * 初始化请求id
     * @return
     */
    public static String initRequestId() {
        String fastSimpleUUID = IdUtil.fastSimpleUUID();
        ThreadContextTool.put(REQUEST_ID_KEY,fastSimpleUUID);
        return fastSimpleUUID;
    }

    /**
     *
     * @param requestId
     * @return
     */
    public static String initRequestId(String requestId){
        if (StrUtil.isNotBlank(requestId)) {
            restoreRequestId(requestId);
            return requestId;
        }
        return initRequestId();
    }
    /**
     * 获取请求id
     * @return
     */
    public static String getRequestId() {
        return ((String) ThreadContextTool.get(REQUEST_ID_KEY));
    }

    /**
     * 覆盖请求id
     * @param requestId
     */
    public static void restoreRequestId(String requestId){
        ThreadContextTool.remove(REQUEST_ID_KEY);
        ThreadContextTool.put(REQUEST_ID_KEY,requestId);
    }
}
